﻿using System;
using System.Collections.Generic;
using System.Linq;
using SecurityLog.Models;

namespace SecurityLog.Repositories
{
    public class UsersRepository : IUsersRepository
    {
        private readonly ModelDataContext _ctx;

        public UsersRepository()
            :this(new ModelDataContext())
        {
        }

        public UsersRepository(ModelDataContext ctx)
        {
            _ctx = ctx;
        }

        public Models.User CreateNewUser(string name, string initials, string password, bool enabled)
        {
            Models.User u = new Models.User
            {
                Name = name,
                Initials = initials.ToUpper(),
                Password = password,
                Enabled = enabled
            };

            _ctx.Users.InsertOnSubmit(u);
            _ctx.SubmitChanges();

            return u;
        }

        public Models.User EditUser(int id, string name, string initials, string password, bool enabled)
        {
            Models.User u = GetUserById(id);

            u.Name = name;
            u.Initials = initials.ToUpper();
            u.Enabled = enabled;

            if(!String.IsNullOrEmpty(password))
                u.Password = password;

            _ctx.SubmitChanges();

            return u;
        }

        public Models.User GetUserById(int id)
        {
            Models.User u = _ctx.Users.SingleOrDefault(x => x.Id == id);
            if (u == null)
                throw new ArgumentException("No user found with id = '" + id + "'");

            return u;
        }

        public IEnumerable<Models.User> GetAllUsers()
        {
            return _ctx.Users.OrderBy(x => x.Name);
        }

        public void DeleteUser(int id)
        {
            Models.User u = GetUserById(id);
            if (u != null)
            {
                _ctx.Users.DeleteOnSubmit(u);
                _ctx.SubmitChanges();
            }
        }

        public void ToggleUser(int id)
        {
            Models.User u = GetUserById(id);
            if (u != null)
            {
                u.Enabled = !u.Enabled;
                _ctx.SubmitChanges();
            }
        }

        public bool IsEnabled(int id)
        {
            Models.User u = GetUserById(id);
            return u != null && u.Enabled;
        }

        public bool Validate(string initials, string password)
        {
            return GetUser(initials, password) != null;
        }

        public Models.User GetUser(string initials, string password)
        {
            return _ctx.Users.SingleOrDefault(x => x.Initials == initials && x.Password == password);
        }
    }
}